/*
 * @Author: liqing
 * @Date: 2022-03-29 11:18:39
 * @LastEditors: liqing
 * @LastEditTime: 2023-08-02 14:51:25
 * @Description: description
 * DEMO参考文档：https://www.jianshu.com/p/f439ce5cc0be
 * 注意socket.io的版本：
 * 如果使用4.x版本，io.sockets.adapter.rooms[room]无法获得房间信息（3.x版本以后rooms返回的是Set，不再是对象了）
 * 如果使用2.0.3版本，navigator.mediaDevices.getUserMedia不可用（未验证需要如何修改）
 */
'use strict'

var express = require('express');
var fs = require('fs');
var app = express();

const options = {
  key: fs.readFileSync('./cakey.pem').toString(),
  cert: fs.readFileSync('./cacert.pem').toString(),
};

// var http = require('https').createServer(options, app);
var http = require('http').createServer(app);
// socket.io API地址：https://www.w3cschool.cn/socket
var io = require('socket.io')(http);

// 静态资源代理
app.use('/css', express.static('css'));
app.use('/js', express.static('js'));
app.use('/img', express.static('img'));
app.use('/module', express.static('module'));

// 路由配置
// app.get('/', function (request, response) {
//     response.sendFile(__dirname + '/index.html');
// });

app.get('/userA', function (request, response) {
  response.sendFile(__dirname + "/userA.html")
});

app.get('/userB', function (request, response) {
  response.sendFile(__dirname + "/userB.html")
});

app.get('/userC', function (request, response) {
  response.sendFile(__dirname + "/userC.html")
});

app.get('/rtsp', function (request, response) {
  response.sendFile(__dirname + "/index.html")
});

io.on('connection', function (socket) {
  console.log(`有用户加入进来 and socket.id is ${socket.id}`);
  socket.on('signal', function (message) {
    socket.to('room').emit('signal', message);
  });

  socket.on('ice', function (message) {
    socket.to('room').emit('ice', message);
  });

  socket.on('create or join', function (room) {
    // 当前使用的socket.io版本为4.4.1，原代码中io.sockets.adapter.rooms返回的已经不是对象，而是一个Set，因此原来的io.sockets.adapter.rooms[room]必定返回undefined
    var clientsInRoom = io.sockets.adapter.rooms.get(room);
    if (typeof clientsInRoom === "undefined") {
      socket.join(room);
      socket.emit('create', room, socket.id);
      console.log('caller joined');
    } else {
      socket.join(room);
      socket.to(room).emit('call');
      console.log('callee joined');
    }
  });
});

/**
 * 注意：如果定义的是http server，则在访问页面时会禁止页面调用摄像头/麦克风设备
 * 规避方案：访问chrome://flags/，找到Insecure origins treated as secure配置项，把http://192.168.0.106:8080加入例外清单
 * 本地运行时需要把下面的IP替换成本地的IP
 */
var server = http.listen(9999, '127.0.0.1', function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log(`listening on:http://${host}:${port}`);
});

/**
 * 服务端代码不涉及任何webRTC内容，socket.io同步的消息不涉及音视频流
 */

